import urllib
import re

current_index = 0
current_keyword = None
query_url = 'http://www.youtube.com/results?search_query=%s&aq=f'
youtube = "http://youtube.com"
href = "href="
video_urls = []

def findVideo(keyword):
  global current_index, current_keyword, video_urls
  if current_keyword != keyword:
    print query_url % keyword
    html = urllib.urlopen(query_url % keyword).readlines()
    current_index = 0
    current_keyword = keyword
    video_urls = []
    for line in html:
      index = line.find(href)
      if index >= 0:
        video = line[index + len(href):]
        match = re.search('/watch\?v=(([A-Za-z0-9]|_|-)+)', video)
        if match:
          if not youtube + match.group(0) in video_urls:
            video_urls.append(youtube + match.group(0))
  else:
    current_index += 1
    current_index %= len(video_urls)
  return video_urls[current_index]

  
